from flask import Flask, render_template, request, redirect, url_for
from flask_mysqldb import MySQL
import os
import uuid

app = Flask(__name__)

# 配置MySQL
app.config['MYSQL_HOST'] = '10.200.36.30'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = '111111'
app.config['MYSQL_DB'] = 'f21010212'

# 初始化MySQL
mysql = MySQL(app)

# 设置上传文件夹
UPLOAD_FOLDER = 'uploads'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/upload', methods=['POST'])
def upload():
    if request.method == 'POST':
        if 'file' not in request.files:
            return redirect(request.url)
        file = request.files['file']
        if file.filename == '':
            return redirect(request.url)
        if file:
            filename = str(uuid.uuid4()) + '.' + file.filename.split('.')[1]
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            question_text = request.form.get('question_text')
            cursor = mysql.connection.cursor()
            cursor.execute('''INSERT INTO questions (image_path, question_text) VALUES (%s, %s)''', (filename, question_text,))
            mysql.connection.commit()
            cursor.close()
            return 'File uploaded successfully'

@app.route('/get_answers/<int:question_id>')
def get_answers(question_id):
    cursor = mysql.connection.cursor()
    cursor.execute('''SELECT answer_text FROM questions WHERE id = %s''', (question_id,))
    answer = cursor.fetchone()
    cursor.close()
    if answer:
        return answer[0]  # 返回答案文本
    else:
        return 'No answer found'

if __name__ == '__main__':
    app.run(debug=True)